<template>
  <view>
    <!-- v-show="!showCouponPopup" -->
    <view class="main-container" style="background-color: #dd302c">
      <!-- 顶部导航 -->
      <view class="nav-bar">
        <view class="nav-left" @tap="handleBack">
          <u-icon name="arrow-left" color="#FFF" size="20"></u-icon>
        </view>
        <view class="nav-title">人工智能易学大模型</view>
        <view class="nav-right" @tap="handleBack">
          <u-icon name="close" color="#FFF" size="20"></u-icon>
        </view>
      </view>

      <!-- 用户信息区 -->
      <view class="user-info-area">
        <view class="user-name-row">
          <text class="user-name">{{ userInfo.userName }}</text>
          <view class="user-action-buttons">
            <view class="action-button" @tap="handleBackHome">
              <image
                src="/static/images/icon-return.png"
                class="action-icon"
              ></image>
              <text class="action-text">重新测算</text>
            </view>
            <!-- <view class="action-button" @tap="handleReport">
              <image src="/static/images/icon-report.png" class="action-icon"></image>
              <text class="action-text">测算报告</text>
            </view> -->
          </view>
        </view>
        <!-- 天干地支信息 -->
        <view class="celestial-container">
          <view class="celestial-stems-branches">
            <view
              class="celestial-item"
              v-for="(item, index) in otherUserInfo.celestialItems"
              :key="index"
            >
              <view class="celestial-icon">{{ item.label }}</view>
              <text class="celestial-text">{{ item.value }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 功能卡片区域 -->
      <view class="function-cards">
        <view
          class="function-card"
          v-for="(card, index) in otherUserInfo.shishenCard"
          :key="index"
        >
          <view class="card-header">
            <view class="category-icon"></view>
            <text class="card-title">{{ card.label }}</text>
          </view>
          <view class="card-content">
            <text class="card-text">{{ card.value }}</text>
          </view>
        </view>
      </view>

      <view class="box-content" style="margin-bottom: 0">
        <!-- 功能介绍 -->
        <view class="feature-section">
          <view class="feature-title">{{ pageData.feature.title }}</view>

          <!-- 婚姻透视tabs和图表 -->
          <view class="insight-layout">
            <view class="tabs-container">
              <view class="tabs-row">
                <view
                  v-for="(tab, index) in pageData.currentTabs"
                  :key="index"
                  class="tab"
                  :class="{ active: currentMarriageTab === index }"
                  @tap="changeMarriageTab(index)"
                >
                  {{ tab.name }}
                  <view
                    class="tab-underline"
                    :class="{ active: currentMarriageTab === index }"
                  ></view>
                </view>
              </view>
              <view class="chart-container">
                <image
                  :src="`/static/images/lineChart${currentMarriageTab + 1}.png`"
                  class="line-chart"
                  mode="widthFix"
                >
                </image>
              </view>
            </view>
            <view class="ai-person-container">
              <image
                src="/static/images/aiperson.png"
                class="ai-person"
                mode="widthFix"
              ></image>
            </view>
          </view>

          <view class="messageText">
            <typewriter-text
              :text="pageData.askMessage"
              :typing-speed="150"
            ></typewriter-text>
          </view>

          <!-- 未支付时显示价格和支付按钮 -->
          <template v-if="!getPayStatus('marriage')">
            <!-- 价格信息 -->
            <view class="price-section">
              <view class="price-wrapper">
                <text class="original-price">原价￥{{ originalPrice }}</text>
                <text class="current-price"
                  >结缘价：{{ currentPrice }}元</text
                >
              </view>
              <view class="discount-timer">
                <text>距离结束：{{ countdownTime }}</text>
              </view>
            </view>
            <!-- 支付按钮 -->
            <view id="pay-button" class="pay-button" @tap="createOrder">
              <text class="button-text">{{ pageData.payButton }}</text>
            </view>

            <view class="user-count"
              >已有
              <span style="color: #dd302c">{{
                Math.floor(userCount * 0.86)
              }}</span
              >人完成支付，获取了姻缘分析结果</view
            >
            <view class="otherComp-image">
              <image :src="pageData.feature.otherComp" mode="aspectFit"></image>
            </view>

            <view class="messageText" style="color: #666">
              <text>{{ pageData.payMessage }}</text>
            </view>
          </template>
        </view>
      </view>
      <view class="transition-image">
        <image :src="pageData.transitionImage" mode="aspectFit"></image>
      </view>

      <!-- 基本信息卡片 -->
      <view class="box-content">
        <view class="title-icon">
          <view class="title-text">基本信息</view>
        </view>
        <view class="info-content">
          <table class="info-table">
            <thead>
              <tr>
                <th
                  v-for="(header, index) in otherUserInfo.basicInfo.headers"
                  :key="index"
                >
                  {{ header }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{{ userInfo.surname }}</td>
                <td>{{ userInfo.gender }}</td>
                <td>
                  <view class="date-container">
                    <view class="date-row">
                      <text>公历：{{ userInfo.solarDay || "年月日" }}</text>
                    </view>
                    <view class="date-row">
                      <text>农历：{{ userInfo.lunarDay || "年月日" }}</text>
                    </view>
                  </view>
                </td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 生辰排盘 -->
      <view class="box-content">
        <view class="title-icon">
          <view class="title-text">生辰排盘</view>
        </view>
        <view class="info-content">
          <table class="info-table">
            <thead>
              <tr>
                <th
                  v-for="(header, index) in otherUserInfo.birthChart.headers"
                  :key="index"
                >
                  {{ header }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td
                  v-for="(value, index) in otherUserInfo.birthChart.subHeaders"
                  :key="index"
                >
                  {{ value }}
                </td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 格局分析 -->
      <view class="box-content">
        <view class="title-icon">
          <view class="title-text">格局分析</view>
        </view>
        <view class="info-content">
          <view class="pattern-desc">{{
            otherUserInfo.patternAnalysis.description
          }}</view>
          <table class="info-table pattern-table">
            <thead>
              <tr>
                <th
                  v-for="(header, index) in otherUserInfo.patternAnalysis
                    .headers"
                  :key="index"
                >
                  {{ header }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td
                  v-for="(value, index) in otherUserInfo.patternAnalysis.data"
                  :key="index"
                >
                  {{ value }}
                </td>
              </tr>
            </tbody>
          </table>
        </view>
      </view>

      <!-- 功能列表 -->
      <view
        class="box-content"
        style="background: linear-gradient(to bottom, #f7d1d5 0%, #ffffff 3%)"
      >
        <view class="title-icon">
          <view class="title-text" style="min-height: 20px"> </view>
        </view>
        <view class="feature-box">
          <view class="feature-content-bg">
            <view
              class="feature-content-item"
              v-for="(item, index) in marriageResultInfo.featureList"
              :key="index"
            >
              <view class="feature-content"> {{ item.thinkContent }} </view>
            </view>
          </view>
          <view class="feature-list" @tap="createOrder">
            <view
              class="feature-item"
              v-for="(item, index) in marriageResultInfo.featureList"
              :key="index"
            >
              <view class="feature-title">立即查看{{ item.title }}</view>
              <view class="feature-content">
                <typewriter-text
                  :text="
                    '人工智能大模型推理中:' +
                    getThinkContentPrefix(item.thinkContent)
                  "
                  :typing-speed="200"
                ></typewriter-text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单列表 -->
      <view class="box-content">
        <view class="info-content">
          <view class="order-list-container">
            <!-- Original items -->
            <view
              class="order-item"
              v-for="(item, index) in orderList"
              :key="index"
            >
              <text>{{ item.id }}</text>
              <text>{{ item.date }}</text>
              <text>{{ item.price }}</text>
            </view>
            <!-- Duplicated items for seamless scrolling -->
            <view
              class="order-item"
              v-for="(item, index) in orderList"
              :key="'dup-' + index"
            >
              <text>{{ item.id }}</text>
              <text>{{ item.date }}</text>
              <text>{{ item.price }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部信息 -->
      <view class="footer-info">
        <text class="slogan">先进·专业·高标准·值得信赖</text>
        <text class="sub-text"
          >平台所有产品拒绝向未成年人提供服务，仅供娱乐和参考！</text
        >
        <text class="copyright">2025AI 易学大揭型 全年无休</text>
        <view
          class="footer-button"
          @tap="createOrder"
          v-if="!getPayStatus('marriage')"
        >
          立即查看
        </view>
      </view>

      <!-- 固定底部按钮 -->
      <view
        class="fixed-button"
        :class="{ hidden: !showFixedButton }"
        @tap="createOrder"
        v-if="!getPayStatus('marriage')"
      >
        立即查看
      </view>
    </view>
    <!-- 优惠券 -->
    <coupon-popup
      :visible="showCouponPopup"
      :userInfo="userInfo"
      @close="closeAndReturn"
      @import-coupon="useCoupon"
    />

    <!-- 支付状态确认弹窗 -->
    <!-- <pay-status-dialog :visible="showPayStatusDialog" @confirm="confirmPayment" @retry="createOrder" /> -->

    <!-- 手机号输入弹窗 -->
    <phone-input-dialog
      :visible="showPhoneDialog"
      @close="closePhoneDialog"
      @success="handlePhoneSuccess"
      :post="phonePost"
    />
    <floating-report ref="report" />
  </view>
</template>

<script>
import { queryOrder } from "@/api/fortune";
import CouponPopup from "@/components/CouponPopup/index.vue";
// import PayStatusDialog from '@/components/dialog/PayStatusDialog.vue';
import PhoneInputDialog from "@/components/dialog/PhoneInputDialog.vue";
import { trackButton, trackPageView, trackPayment } from "@/utils/track";
import { mapActions, mapGetters } from "vuex";
import pageData from "./data.js";

function getRandomId() {
  const num = Math.floor(1000 + Math.random() * 9000);
  return `易学大模型AID25***${num}`;
}
function getRandomDate() {
  const now = new Date();
  const daysAgo = Math.floor(Math.random() * 30);
  const date = new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000);
  const y = date.getFullYear();
  const m = date.getMonth() + 1;
  const d = date.getDate();
  return `${y}-${m}-${d}`;
}
function getRandomPrice() {
  return Math.random() > 0.5 ? "39.8元" : "29.8元";
}
function generateOrderList(count = 12) {
  const list = [];
  for (let i = 0; i < count; i++) {
    list.push({
      id: getRandomId(),
      date: getRandomDate(),
      price: getRandomPrice(),
    });
  }
  return list;
}

export default {
  name: "PayPage",
  components: {
    CouponPopup,
    // PayStatusDialog,
    PhoneInputDialog,
  },
  data() {
    return {
      pageData,
      // 价格相关
      originalPrice: pageData.price.original,
      currentPrice: pageData.price.current,
      finalPrice: pageData.price.final,
      // 当前选中的婚姻透视tab
      currentMarriageTab: 0,
      orderList: [],
      countdownTime: "", // 倒计时时间
      timer: null, // 定时器
      showCouponPopup: false, // 是否显示优惠券弹窗
      hasCoupon: false, // 是否使用优惠券
      couponUsed: false, // 添加标记优惠券是否已使用

      showFixedButton: false,
      pageViewTracker: null,

      currentorderNo: "", //支付订单
      showPayStatusDialog: false, //支付状态弹窗
      showPhoneDialog: false, // 手机号输入弹窗
      phonePost: true,
    };
  },

  computed: {
    ...mapGetters("fortune", [
      "marriageResultInfo",
      "otherUserInfo",
      "userInfo",
    ]),
    ...mapGetters("system", ["userCount", "userPhone"]),
    ...mapGetters("payment", ["getPayStatus"]),
  },

  created() {
    this.orderList = generateOrderList(12);
    this.startCountdown();
  },

  mounted() {
    // 启动页面浏览埋点计时
    this.pageViewTracker = trackPageView({
      reportKey: "进入支付预览页",
      reportVal: "浏览",
      pageName: "支付预览页",
    });
    this.pageViewTracker.start();
  },

  // 页面显示时检查是否从支付页面返回
  onShow() {
    // 使用工具函数获取解码后的订单号
    const decodedOrderNo = this.$utils.getDecodedUrlParam("orderNo");
    if (decodedOrderNo) {
      // 清除URL参数中的orderNo，避免重复处理
      const newUrl = window.location.pathname;
      window.history.replaceState({}, document.title, newUrl);
      // 记录订单号
      this.currentorderNo = decodedOrderNo;
      // 直接验证支付状态
      this.confirmPayment();
    }
  },

  methods: {
    // 启动倒计时
    startCountdown(val = "10:00:00") {
      // 如果传入了新的时间值，使用新值；否则使用默认的10分钟
      this.countdownTime = val;
      let [minutes, seconds, milliseconds] = this.countdownTime
        .split(":")
        .map(Number);
      let totalMilliseconds = minutes * 60000 + seconds * 1000 + milliseconds;

      this.timer = setInterval(() => {
        totalMilliseconds -= 10; // 每10毫秒更新一次
        if (totalMilliseconds <= 0) {
          clearInterval(this.timer);
          this.timer = null;
          this.countdownTime = "00:00:00";
          return;
        }

        const m = Math.floor(totalMilliseconds / 60000);
        const s = Math.floor((totalMilliseconds % 60000) / 1000);
        const ms = Math.floor((totalMilliseconds % 1000) / 10);
        this.countdownTime = `${m.toString().padStart(2, "0")}:${s
          .toString()
          .padStart(2, "0")}:${ms.toString().padStart(2, "0")}`;
      }, 100);
    },
    // 切换婚姻透视tab
    changeMarriageTab(index) {
      this.currentMarriageTab = index;
    },

    // 发起订单
    createOrder() {
      uni.showLoading({ title: "正在创建订单...", mask: true });
      trackButton({
        reportKey: "发起支付按钮",
        reportVal: "发起支付",
        pageName: "支付预览页",
      });
      const orderParams = {
        goodsId: "20250618001", // 商品ID
        payAmount: this.currentPrice,
        redirect: "/pages/pay/index",
      };

      this.$commonPay(orderParams);
      uni.hideLoading();
    },

    // 确认支付完成
    confirmPayment() {
      uni.showLoading({ title: pageData.payMessages.loading, mask: true });

      // 校验支付状态
      this.verifyPaymentStatus(this.currentorderNo, (success) => {
        uni.hideLoading();
        if (success) {
          // 支付验证成功，执行原来的成功逻辑
          trackPayment({
            reportKey: "支付成功",
            reportVal: this.currentorderNo,
            pageName: "支付预览页",
          });
          this.$store.dispatch("payment/setPayStatus", {
            type: "marriage",
            status: true,
          });
          this.showPhoneDialog = true;
        } else {
          // 支付验证失败

          // this.$show.showToast(pageData.payMessages.failure, { icon: "error" });
          this.$show.showToast('支付失败');
          if (!this.couponUsed) this.showCouponPopup = true;
          trackPayment({
            reportKey: "支付失败",
            reportVal: this.currentorderNo,
            pageName: "支付预览页",
          });
        }
      });
    },

    // 校验支付状态
    verifyPaymentStatus(orderNo, callback) {
      // 使用正确的 API 接口验证支付状态
      queryOrder(orderNo)
        .then((res) => {
          // 适配新接口，orderPayStatus为1表示支付成功
          this.$show.showToast(res.data);
          if (res.code === 0 && res.data && res.data.orderPayStatus === 1) {
            callback(true);
          } else {
            callback(false);
          }
        })
        .catch((err) => {
          callback(false);
        });
    },

    handleReport() {
      // 跳转到测算报告页面
      uni.navigateTo({
        url: "/pages/report/index",
      });
    },
    // handleThink() {
    //   // 如果未支付，滚动到支付按钮位置
    //   if (!this.getPayStatus('marriage')) {
    //     this.scrollToPayButton();
    //     return;
    //   }
    //   // 已支付，跳转到报告页面
    //   uni.navigateTo({
    //     url: '/pages/payResult/result',
    //   });
    // },

    // // 滚动到支付按钮位置
    // scrollToPayButton() {
    //   const payButton = document.getElementById('pay-button');
    //   if (payButton) {
    //     payButton.scrollIntoView({
    //       behavior: 'smooth',
    //       block: 'center'
    //     });
    //   }
    // },

    // 关闭优惠券并返回首页
    closeAndReturn() {
      this.showCouponPopup = false;
    },

    // 使用优惠券
    useCoupon() {
      if (this.couponUsed) {
        this.$show.showToast("优惠券已使用过，不能重复使用");
        return;
      }
      this.hasCoupon = true;
      this.couponUsed = true; // 标记优惠券已使用
      this.showCouponPopup = false;
        // 使用优惠券后的价格
        this.currentPrice = this.finalPrice;
      // 埋点：使用优惠券支付行为
      trackPayment({
        reportKey: "使用优惠券支付",
        reportVal: this.currentorderNo,
        pageName: "支付预览页",
      });
    
    },

    // 处理返回和关闭
    handleBack() {
      uni.reLaunch({
        url: "/pages/home/index",
      });
    },
    handleBackHome() {
      // 重置所有支付状态
      this.$store.dispatch("payment/resetPayStatus");
      uni.reLaunch({
        url: "/pages/home/index",
      });
    },

    // 关闭手机号弹窗
    closePhoneDialog() {
      this.showPhoneDialog = false;
    },

    // 手机号绑定成功回调
    handlePhoneSuccess(phoneNumber) {
      this.showPhoneDialog = false;
      this.$show.showToast(pageData.payMessages.success, {
        icon: "success",
        success: () => {
          uni.navigateTo({ url: "/pages/payResult/result" });
        },
      });
    },

    // 新增：统一处理冒号并分割
    getThinkContentPrefix(content) {
      if (!content) return "";
      const normalized = content.replace(/：|:/g, ":");
      return normalized.split(":")[0] + "...";
    },
  },

  onUnload() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    // 页面卸载时也停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },

  onPageScroll({ scrollTop }) {
    // 获取支付按钮和底部信息的位置
    const query = uni.createSelectorQuery();
    query.select(".pay-button").boundingClientRect();
    query.select(".footer-info").boundingClientRect();
    query.selectViewport().scrollOffset();

    query.exec(([payButtonRect, footerRect, scrollOffset]) => {
      if (payButtonRect && footerRect) {
        const windowHeight = uni.getSystemInfoSync().windowHeight;

        // 判断是否滚动到底部区域
        const isNearBottom = footerRect.top <= windowHeight + 100;

        // 判断支付按钮是否在可视区域内
        const isPayButtonVisible =
          payButtonRect.top >= 0 && payButtonRect.bottom <= windowHeight;

        // 当接近底部或支付按钮可见时，隐藏固定按钮
        this.showFixedButton = !isNearBottom && !isPayButtonVisible;
      }
    });
  },

  onHide() {
    // 页面离开时停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
};
</script>

<style lang="scss" scoped>
@import "./pay.scss";
</style>
